import {
    tips
} from "./tips";
import {
    getToken,
    getConn,
} from "@/store/user.js";

const errHandler = (err) => {
    if (err?.data?.msg) tips("错误", err?.data?.msg);
    else tips("错误", "操作失败");
    return Promise.reject(err);
};

export const fetch = (method, url, params = {}, data = {}, errMsg, hasToken = true) =>
    new Promise(async (resolve, reject) => {
        const that = this;
        const token = getToken();
        let header = {
            Accept: "application/json, text/plain, */*",
            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
            "content-type": "application/json",
        };
        if (hasToken) {
            header['Token'] = token;
        }
        let arr = [];
        for (const key in params) {
            if (Object.hasOwnProperty.call(params, key)) {
                const element = params[key];
                if (element) arr.push(`${key}=${element}`);
            }
        }

        let baseUrl = '';
        // #ifdef H5
        // 如需跨域参照以下h5跨域配置
        baseUrl = "/api"
        // #endif

        // #ifdef APP-PLUS
        baseUrl = getConn().wms;
        console.log('fetch url =>', `${baseUrl}${url}${arr.length > 0 ? "?" + arr.join("&") : ""}`);
        // #endif

        uni.request({
            method,
            url: `${baseUrl}${url}${arr.length > 0 ? "?" + arr.join("&") : ""}`,
            header,
            data,
            success(res) {
                if (res.data.code == "1") {
                    return resolve(res.data.data);
                } else {
                    return reject(res.data);
                }
            },
            fail(err) {
                return reject(err);
            },
            complete(res) {
                // console.log('url', url);
                // console.log('data', data);
                // console.log('res', res);
                if (res.data.code == 401) {
                    uni.redirectTo({
                        url: '/pages/login/index'
                    });
                }
            },
        });
    }).catch((res) => {
        tips("错误", errMsg ? errMsg : res.msg ? res.msg : "服务器异常...");
        return Promise.reject({});
    });
export default fetch;